package io.jft.doll.ui.inputInviteCode

import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.extend.observeEx
import com.g.base.extend.resultNotNull
import com.g.base.extend.toast
import com.g.base.help.postSimpleNotify
import com.g.base.room.repository.Status
import com.g.base.ui.BaseActivity
import io.jft.doll.R
import io.jft.doll.databinding.ActivityInputShareBinding
import io.jft.doll.event.NotifyUrl
import io.jft.doll.model.viewModel.UserViewModel
import io.jft.doll.room.entity.remote.InviteInfoREntity
import io.jft.doll.router.RouterPage

@Route(path = RouterPage.InputInviteCodeActivity)
class InputInviteCodeActivity : BaseActivity<ActivityInputShareBinding>() {
    override var isFullScreen: Boolean = true
    override var hasToolbar: Boolean = true

    private val userViewModel by lazy { ViewModelProviders.of(this).get(UserViewModel::class.java) }
    var data: InviteInfoREntity? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setContentView(R.layout.activity_input_share)
        initView()
        obsData()
    }

    private fun initView() {
        toolbar.title = "输入邀请码"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener { finishAfterTransition() }
    }

    private fun obsData() {
        userViewModel.operateInviteInfo()
        userViewModel.obsInviteInfo()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> showLoading()
                        Status.Content -> {
                            data = it.data!!
                            contentView.data = this
                            showContentView()
                        }
                        else -> showError()
                    }
                }
    }

    fun onCommitClick(view: View) {
        if (contentView.input.text.length < 6) {
            toast("邀请码无效,请输入正确的邀请码")
            return
        }
        userViewModel.inputInviteCode(contentView.input.text.toString())
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> toast("正在处理中...")
                        Status.Content -> {
                            toast("兑换成功")
                            postSimpleNotify(NotifyUrl.UserRemaining)
                            finishAfterTransition()
                        }
                        Status.Error -> {
                            toast(it.error?.message ?: "未知错误~")
                        }
                    }
                }
    }
}